package com.zzj.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzj.entity.Chat;
import com.zzj.entity.ChatFriends;
import com.zzj.mapper.ChatMapper;
import com.zzj.service.IChatFriendsService;
import com.zzj.service.IChatService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 聊天表 服务实现类
 * </p>
 *
 * @author zzj
 * @since 2023-05-13
 */
@Service
public class ChatServiceImpl extends ServiceImpl<ChatMapper, Chat> implements IChatService {
    @Resource
    private IChatFriendsService chatFriendsService;
    @Override
    public boolean createChat(String fromUsername, String toUsername, String message, int type, int size) {
        ChatFriends one = chatFriendsService.getOne(Wrappers.<ChatFriends>lambdaQuery()
                        .eq(ChatFriends::getFromUsername, fromUsername)
                        .eq(ChatFriends::getToUsername, toUsername),
                false);

        Chat chat = new Chat();
        chat.setFromUsername(one.getFromUsername());
        chat.setFromName(one.getFromName());
        chat.setFromAvatar(one.getFromAvatar());
        chat.setToUsername(one.getToUsername());
        chat.setToName(one.getToName());
        chat.setToAvatar(one.getToAvatar());
        chat.setContent(message);
        chat.setType(type);
        chat.setSize(size);
        boolean save = this.save(chat);
        return save;
    }

    @Override
    public Chat lastChat(String fromUsername, String toUsername) {
        return this.getOne(Wrappers.<Chat>lambdaQuery()
                .eq(Chat::getToUsername, toUsername)
                .or(i -> {
                    i.eq(Chat::getFromUsername, toUsername)
                            .eq(Chat::getToUsername, fromUsername);
                }).orderByDesc(Chat::getCreateTime).last("limit 1"));
    }
}
